<?php

namespace app\command;

use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\console\input\Argument;
use think\console\input\Option;
use think\facade\App;

class MakeModel extends Command
{
    protected function configure()
    {
        $this->setName('make:model')
            ->addArgument('name', Argument::REQUIRED, '模型名称')
            ->addOption('extend', null, Option::VALUE_REQUIRED, '继承的父类')
            ->addOption('module', null, Option::VALUE_REQUIRED, '模块名称，默认为 app');
    }

    protected function execute(Input $input, Output $output)
    {
        $name = ucfirst($input->getArgument('name'));
        $extendClass = $input->getOption('extend') ?: 'Model';
        $module = $input->getOption('module');

        // 获取模板路径
        $stubPath = App::getAppPath() . 'command' . DIRECTORY_SEPARATOR . 'templates' . DIRECTORY_SEPARATOR . 'model.tpl';

        if (!file_exists($stubPath)) {
            $output->writeln("<error>模型模板文件不存在</error>");
            return;
        }

        $content = file_get_contents($stubPath);

        // 修改：处理 module 为空的情况
        $namespace = $module ? "app\\{$module}\\model" : "app\\model";

        // 替换变量
        $content = str_replace(
            ['{{className}}', '{{tableName}}', '{{extendClass}}', '{{namespace}}'],
            [$name, strtolower($name), $extendClass, $namespace],
            $content
        );

        // 写入目标文件
        $modelPath = app_path() . "{$module}/model/{$name}.php";
        if (!is_dir(dirname($modelPath))) {
            mkdir(dirname($modelPath), 0755, true);
        }
        file_put_contents($modelPath, $content);

        $output->writeln("模型 {$name} 已生成，继承自 {$extendClass}，位于模块 {$module}");
    }
}
